/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.app.service.impl;

import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.HttpHeaders;
import org.apache.log4j.Logger;
import org.app.utils.PropertiesHelper;
import org.app.utils.PropertyUtils;
import org.gui.AutoDownloadMovieGUI;
import org.jsoup.Connection;

/**
 *
 * @author LamLe
 */
public abstract class GoogleAbstract {

    private static Logger logger = Logger.getLogger(GoogleAbstract.class);
    AutoDownloadMovieGUI main;

    public GoogleAbstract(AutoDownloadMovieGUI main) {
        this.main = main;
    }

    public void initRequestHeader(HttpURLConnection conn, String host) throws Exception {
        try {
            conn.setRequestMethod("GET");
            conn.setRequestProperty(HttpHeaders.HOST, host);
            conn.setRequestProperty(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0");
            conn.setRequestProperty(HttpHeaders.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            conn.setRequestProperty(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.5");
            conn.setRequestProperty(HttpHeaders.ACCEPT_ENCODING, "gzip,deflate,sdch");
            conn.setRequestProperty("Connection", "keep-alive");
        } catch (Exception e) {
            logger.error("Failed", e);
        }
    }

    public String generateUrl(String movieName) {
        try {
            movieName = PropertyUtils.getProperty(PropertiesHelper.PREMIUM_SITE) + " " + movieName;
            movieName = movieName.replace(" ", "+");
        } catch (Exception e) {
            logger.error("Failed", e);
        }
        return movieName;
    }

    public void log(String str) {
        main.write(str);
    }

    public String getResponseHeader(HttpURLConnection conn, String key) throws Exception {
        String retVal = "";
        try {
            for (Map.Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) {
                if (header.getKey() != null) {
                    if (header.getKey().equalsIgnoreCase(key)) {
                        retVal = header.getValue().toString();
                        break;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Failed", e);
            throw e;
        }
        return retVal;
    }
}
